<script setup>
import { ref, computed } from 'vue'
import { useLexicalComposer } from 'lexical-vue'
import { $getRoot } from 'lexical'
import { NIcon } from 'naive-ui'
import { Send, Loader, FolderPlus } from '@vicons/tabler'
import { NTooltip } from 'naive-ui'
const editor = useLexicalComposer()
const sendStatus = ref('idle') // 'idle', 'sending', 'responding'
const isDisabled = ref(true)

const buttonText = computed(() => {
  switch (sendStatus.value) {
    case 'sending':
      return '发送中'
    case 'responding':
      return '回复中'
    default:
      return '发送'
  }
})

const buttonIcon = computed(() => {
  return sendStatus.value === 'idle' ? Send : Loader
})

function handleSend() {
  if (isDisabled.value || sendStatus.value !== 'idle') return

  editor.update(() => {
    const root = $getRoot()
    const content = root.getTextContent().trim()
    if (content) {
      sendStatus.value = 'sending'
      emit('send', content)
    }
  })
}
function handleNewChat() {
  emit('newChat')
}

editor.registerUpdateListener(() => {
  editor.update(() => {
    const root = $getRoot()
    isDisabled.value = !root.getTextContent().trim()
  })
})

defineExpose({
  handleSend,
  setSendStatus: (status) => {
    sendStatus.value = status
  }
})

const emit = defineEmits(['send', 'newChat'])
</script>

<template>
  <div v-if="isDisabled" class="absolute bottom-0 left-0 p-5 text-gray-400 text-xs flex flex-col">
    <span>按 ↩︎ 发送</span>
    <span>按 ctrl+Enter 换行</span>
  </div>
  <div class="flex justify-end items-center p-5 absolute bottom-0 right-0 gap-2">
    <n-tooltip raw :show-arrow="false" >
      <template #trigger>
        <CustomButton @click="handleNewChat">
          <template #icon>
            <n-icon size="20" :component="FolderPlus"></n-icon>
          </template>
        </CustomButton>
      </template>
      <span class="px-3 py-2 text-black text-lg font-medium bg-white rounded-md">新建对话</span>
    </n-tooltip>

    <CustomButton
      type="primary"
      :class="{ 'opacity-50 cursor-not-allowed': isDisabled || sendStatus !== 'idle' }"
      @click="handleSend"
    >
      <template #icon>
        <n-icon
          size="20"
          :component="buttonIcon"
          :class="{ 'animate-spin': sendStatus !== 'idle' }"
        ></n-icon>
      </template>
      {{ buttonText }}
    </CustomButton>
  </div>
</template>

<style scoped>
.animate-spin {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
